package ru.alperez.gpsdub.adapter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import ru.alperez.gpsdub.R;
import ru.alperez.model.GpsPoint;
import ru.alperez.util.Converter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

public class MainListAdapter extends ArrayAdapter<GpsPoint>{
	private LayoutInflater inflater;
	
	public MainListAdapter(Context context, List<GpsPoint> points) {
		super(context, R.layout.main_list_item, points);
		inflater = LayoutInflater.from(context);
	}
	
	/**
	 * Return new list of locations, presented in this adapter
	 * @return list of GpsPoint
	 */
	public List<GpsPoint> getPoints() {
		int  len = getCount();
		List<GpsPoint> points = new ArrayList<GpsPoint>(len);
		for (int i=0; i<len; i++) {
			points.add(getItem(i));
		}
		return points;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent){
		View row = convertView;
		ItemHolder holder;
		if (row == null) {
			row = inflater.inflate(R.layout.main_list_item, parent, false);
			holder = new ItemHolder(row);
			row.setTag(holder);
		}
		else {
			holder = (ItemHolder) row.getTag();
		}
		GpsPoint item = getItem(position);
		holder.getOrder().setText(item.getOrder() + ".");
		holder.getName().setText(item.getName());
		holder.getCreator().setText(item.getCreator().getName());
		holder.getTime().setText(Converter.gpsDateTimeFromLocation(item.getLocation()));
		
		return row;
	}
	
	
	private class ItemHolder {
		private View base;
		private TextView order;
		private TextView name;
		private TextView creator;
		private TextView time;
		private Button btnChoose;
		private Button btnDelete;
		
		public ItemHolder(View base) {
			this.base = base;
		}
		
		public TextView getOrder() {
			if (order == null) {
				order = (TextView) base.findViewById(R.id.gps_item_order);
			}
			return order;
		}
		
		public TextView getName() {
			if (name == null) {
				name = (TextView) base.findViewById(R.id.gps_item_name);
			}
			return name;
		}
		
		public TextView getCreator() {
			if (creator == null) {
				creator = (TextView) base.findViewById(R.id.gps_item_creator);
			}
			return creator;
		}
		
		public TextView getTime() {
			if (time == null) {
				time = (TextView) base.findViewById(R.id.gps_item_time);
			}
			return time;
		}
		
		public Button getBtnChoose() {
			if (btnChoose == null) {
				btnChoose = (Button) base.findViewById(R.id.gps_item_choose);
			}
			return btnChoose;
		}
		
		public Button getBtnDelete() {
			if (btnDelete == null) {
				btnDelete = (Button) base.findViewById(R.id.gps_item_delete);
			}
			return btnDelete;
		}
	}
}
